﻿using System;
using System.Data;
using System.Data.Entity;
using System.Runtime.Remoting.Messaging;
using System.Web;

namespace Equation.Enterprise.Framework.Domain.Data
{
    public class WebContextStorage : IDbContextStorage
    {
        public WebContextStorage(HttpApplication application) : this(application, string.Empty)
        {
        }

        public WebContextStorage(HttpApplication application, string storageKey)
        {
            if (!string.IsNullOrEmpty(storageKey))
                this.StorageKey = storageKey;
            else
                this.StorageKey = DbContextManager.DefaultStorageKey;

            application.EndRequest += new EventHandler(ApplicationEndRequest);
        }

        void ApplicationEndRequest(object sender, EventArgs e)
        {
            DbContext context = Context;
            if (context != null)
            {
                if (context.Database.Connection.State == ConnectionState.Open)
                    context.Database.Connection.Close();
                context.Dispose();
                HttpContext.Current.Items.Remove(StorageKey);
            }
        }

        public string StorageKey
        {
            get; private set;
        }

        /// <summary>
        /// Store DbContext object
        /// In case of asyn call from web, there'll be no HttpContext, so store it in CallContext instead
        /// </summary>
        public System.Data.Entity.DbContext Context
        {
            get
            {
                DbContext session;
                HttpContext context = HttpContext.Current;
                if (context != null)
                    session = context.Items[StorageKey] as DbContext;
                else
                    session = CallContext.GetData(StorageKey) as DbContext;

                return session;
            }
            set { 
                HttpContext context = HttpContext.Current;

                if (context != null)
                    context.Items[StorageKey] = value;
                else
                    CallContext.SetData(StorageKey, value);
            }
        }
    }
}
